package com.gwm.item.controller;


import com.gwm.common.utils.BeanHelper;
import com.gwm.common.vo.PageResult;
import com.gwm.item.dto.BrandDTO;
import com.gwm.item.pojo.TbBrand;
import com.gwm.item.service.TbBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/brand")
public class BrandController {

    @Autowired
    private TbBrandService brandService;


    @GetMapping(value = "/page",name = "分页查询品牌数据")
    public ResponseEntity<PageResult<BrandDTO>> findByPage(
            @RequestParam("key") String key,
            @RequestParam(value = "page",defaultValue ="1") Integer page,
            @RequestParam(value = "rows",defaultValue = "10") Integer rows,
            @RequestParam("sortBy") String sortBy,
            @RequestParam(value = "desc",defaultValue = "false") Boolean desc
    ){
        PageResult<BrandDTO> pageResult =  brandService.findByPage(key,page,rows,sortBy,desc);
        return ResponseEntity.ok(pageResult);
    }


    /**
     *
     * @param brandDTO
     * @param cids 分类id、
     * @return
     * void Void
     */

    @PostMapping(name = "保存品牌数据")
    public ResponseEntity<Void> save(BrandDTO brandDTO,@RequestParam("cids") List<Long> cids){
         brandService.saveBrandAndCategory(brandDTO,cids);
        return ResponseEntity.ok().build();
    }
    @PutMapping(name = "修改品牌数据")
    public ResponseEntity<Void> update(BrandDTO brandDTO,@RequestParam("cids") List<Long> cids){
         brandService.updateBrandAndCategory(brandDTO,cids);
        return ResponseEntity.ok().build();
    }

    @GetMapping(value = "/of/category",name = "根据分类id查询品牌信息")
    public ResponseEntity<List<BrandDTO>> findBrandListByCategoryId(@RequestParam("id") Long categoryId){
        List<BrandDTO> brandDTOList =brandService.findBrandListByCategoryId(categoryId);
        return ResponseEntity.ok(brandDTOList);
    }


    @GetMapping(value = "/findBrandListByIds",name = "根据品牌ids获取品牌")
    public ResponseEntity<List<BrandDTO>> findBrandListByBrandIdList(@RequestParam("ids") List<Long> ids){
        Collection<TbBrand> tbBrandList = brandService.listByIds(ids);

        List<BrandDTO> brandDTOList = tbBrandList.stream().map(brand -> {
            return BeanHelper.copyProperties(brand, BrandDTO.class);
        }).collect(Collectors.toList());
      return ResponseEntity.ok(brandDTOList);
    }


    @GetMapping(value = "/{id}",name = "根据品牌id获取品牌")
    public ResponseEntity<BrandDTO> findBrandByBrandId(@PathVariable("id") Long brandId){
        TbBrand tbBrand = brandService.getById(brandId);
        return ResponseEntity.ok(BeanHelper.copyProperties(tbBrand,BrandDTO.class));
    }

}
